import 'dart:convert';

import 'package:identification_photo/utils/string_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CacheUtil {
  static CacheUtil? _instance;
  SharedPreferences? _preferences;

  factory CacheUtil() => _instance ??= CacheUtil._initial();

  CacheUtil._initial() {
    init();
  }

  CacheUtil._pre(SharedPreferences prefs) {
    _preferences = prefs;
  }

  static Future<CacheUtil> perInit() async {
    if (_instance == null) {
      SharedPreferences preferences = await SharedPreferences.getInstance();
      _instance = CacheUtil._pre(preferences);
    }
    return _instance!;
  }

  void init() async {
    _preferences ??= await SharedPreferences.getInstance();
  }

  void setString(key, value) {
    _preferences?.setString(key, value);
  }

  void setStringList(key, value) {
    _preferences?.setStringList(key, value);
  }

  void setBool(key, value) {
    _preferences?.setBool(key, value);
  }

  void setDouble(key, value) {
    _preferences?.setDouble(key, value);
  }

  void setInt(key, value) {
    _preferences?.setInt(key, value);
  }

  void setJson(key, value) {
    value = jsonEncode(value);
    _preferences?.setString(key, value);
  }

  Map<String, dynamic>? getJson<T>(key) {
    String? result = _preferences?.getString(key);
    if (StringUtil.isNotEmpty(result)) {
      return jsonDecode(result!);
    }
    return null;
  }

  T? get<T>(key) {
    var result = _preferences?.get(key);
    if (result != null) {
      return result as T;
    }
    return null;
  }

  void clean() {
    _preferences?.clear();
  }

  void remove(key) {
    _preferences?.remove(key);
  }
}
